<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-if="productType != 8" v-model="listQuery.identifier$lk" placeholder="商品编号" class="filter-item" clearable/>
      <el-input v-model="listQuery.name$lk" placeholder="商品名称" class="filter-item" clearable/>
      <!-- <el-input v-if="productType == 5 || productType == 6 || productType == 7" v-model="listQuery.splitSupplier$lk" placeholder="分润供应商" class="filter-item" clearable/> -->
      <Cascader v-model="listQueryCategoryId" ref="listQueryCategoryId" placeholder="商品分类" :options="categoryData"
        :props="props" class="filter-item" style="width: 210px;" />
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item">
        <el-option v-for="item in statusJson" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-if="productType == 0 || productType == 5 || productType == 8" v-model="listQuery.isSample" placeholder="样品" clearable class="filter-item">
        <el-option v-for="item in sampleJson" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-if="productType == 0" v-model="listQuery.type" placeholder="商品类型" clearable class="filter-item">
        <el-option v-for="item in typeJson" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-cascader v-if="productType == 0" class="filter-item" style="width: 210px;" v-model="storeId" :options="storeList"
        :props="{ checkStrictly: true,value:'id',label:'name' }" clearable placeholder="仓位"></el-cascader>
      <el-select v-if="productType == 9" v-model="listQuery.isFinanceProduct" placeholder="2W商品" clearable class="filter-item">
        <el-option v-for="item in isFinanceProductStatusJson" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <!-- <div v-if="productType == 4" class="filter-item">
        众茶优品(微商城)：
        <el-radio-group v-model="listQuery.isMarketProduct">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </div> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" type="success" icon="el-icon-edit" @click="toSave(0)">
        添加
      </el-button>
      <el-button class="filter-item" type="warning" icon="el-icon-sort" @click="handleFrozen">
        上下架
      </el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete" @click="handlePlDelete">
        批量删除
      </el-button>
      <el-button v-if="productType == 0" v-waves class="filter-item" type="success" icon="el-icon-view" @click="checkStore">
        查看仓位
      </el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row row-key="id" style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <!-- <el-table-column label="序号" type="index" align="center" width="60px" /> -->
      <el-table-column label="序号" prop="sequence" align="center" width="80px" />
      <el-table-column label="审核状态" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
          {{ returnValueToLable(row.status,statusJson) }}
        </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品编号" prop="identifier" align="center" />
      <el-table-column label="商品名称" prop="name" align="center" />
      <el-table-column label="商品分类" prop="categoryName" align="center" />
      <!-- <el-table-column v-if="productType == 5 || productType == 6 || productType == 7 || productType == 9" label="分润供应商" prop="splitSupplier" align="center" /> -->
      <el-table-column label="定价" prop="priceText" align="center" />
      <el-table-column v-if="productType == 8" label="积分" prop="score" align="center" />
      <el-table-column label="库存" prop="store" align="center" />
      <el-table-column label="销量" prop="saleNum" align="center" />
      <el-table-column label="仓位" prop="storeName" align="center" />
      <el-table-column label="审核意见" prop="statusRemark" align="center" />
      <el-table-column label="类型" prop="isSeckillText" align="center">
        <template slot-scope="{row}">
          <el-tag type="success">{{ row.isSeckillText }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="productType == 9" label="2W商品" prop="isFinanceProduct" align="center">
        <template slot-scope="{row}">
          <div v-if="row.isFinanceProduct">是</div>
          <div v-else>否</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="500px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" @click="handleDetail(row)">
            查看
          </el-button>
          <el-button v-if="row.marketId" type="primary" size="mini" @click="handleEditPrice(row)">
            修改价格
          </el-button>
          <el-button v-else type="primary" size="mini" @click="toSave(row.id)">
            编辑
          </el-button>
          <el-button v-if="productType == 0 && row.type === 1" type="success" size="mini" @click="uploadZCTProduct(row.id)">
            上传到众茶通小程序
          </el-button>
          <!-- 众茶通小程序普通商品复制到秒杀商品 -->
          <el-button v-if="productType == 0 && row.type === 2 && row.isBlackWhiteList == 0" type="warning" size="mini" @click="uploadSecKillProduct(row.id)">
            上传到秒杀商品
          </el-button>
          <!-- 众茶优选普通商品复制到秒杀商品 -->
          <el-button v-if="productType == 5" type="warning" size="mini" @click="uploadZcyxSecKillProduct(row.id)">
            上传到秒杀商品
          </el-button>
          <!-- 众茶优选普通商品复制到专柜商品 -->
          <el-button v-if="productType == 5" type="success" size="mini" @click="uploadZcyxBarProduct(row.id)">
            上传到专柜商品
          </el-button>
          <!-- 众茶优选普通商品复制到经销商品 -->
          <el-button v-if="productType == 5" type="primary" size="mini" @click="uploadZcyxAgentProduct(row.id)">
            上传到经销商品
          </el-button>
          <!-- 众茶优选专柜商品显示商品二维码 -->
          <el-button v-if="productType == 10" type="success" size="mini" @click="getQRcode(row)">二维码</el-button>
          <el-button v-if="productType == 0 && row.type === 2 && row.isBlackWhiteListActivity == 0" type="success" size="mini" @click="uploadActivityProduct(row.id)">
            上传到活动专区
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />
    
    <el-dialog title="详情" v-if="dialogDetailVisible" :visible.sync="dialogDetailVisible" width="800px">
      <Detail :row="detail" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogDetailVisible = false">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-image-viewer  v-if="qrImageVisible" :on-close="closeViewer" :initial-index="0" :url-list="[this.QRImgUrl]" />
  
    <el-dialog title="编辑" :visible.sync="editDialogFormVisible" width="500px">
      <el-form :model="tempProduct" ref="confirmForm" label-position="right" label-width="100px"
        style="margin: 0 50px;">
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="tempProduct.price" @input="(val) => { handlePriceInput(val, tempProduct, 'price') }" placeholder="请输入"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="finishEditPrice()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  categoryPageVoByQo, 
  productPageByQo, 
  activityProductPageByQo, 
  agentProductPageByQo, 
  secKillProductPageByQo, 
  productFrozen, 
  productRemoveByIds, 
  copyToC, 
  productGetById,
  productSave
 } from '@/api/product'

 import { 
  copyProductToCounter,
  getBarProductQrcode
} from '@/api/zcyx'

import { storePageByQo } from '@/api/store'
import Detail from './detail'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Cascader from '@/components/Cascader'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

export default {
  name: 'CommomProductList',
  directives: { waves },
  props: {
    paramProductType: {
      default: 0,
      type: Number,
    },
  },
  components: { Detail, Cascader, Pagination, ElImageViewer },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success',
        2: '',
        3: 'info'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      // 0:普通商品，
      // 1:秒杀商品，
      // 2:经销商品 
      // 3:活动专区商品 
      // 4:微商城商品 
      // 5:众茶优选普通商品 
      // 6：众茶优选秒杀商品 
      // 7:众茶优选推广秒杀商品 
      // 8:众茶优选积分商品 
      // 9:众茶优选经销商品 
      // 10:众茶优选专柜商品 
      // 11:众茶优品商品 
      // 12:服务商专区商品 
      productType: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        name$lk: '',
        identifier$lk: '',
        categoryId: '',
        status: '',
        storeId: '',
        isSample: '',
        type: '',
        splitSupplier$lk: '',
        isMarketProduct: 0,
        isFinanceProduct: '',
        isServeProduct: 0,
      },
      multipleSelection: [],
      categoryData: [],
      props: { value: 'id', label: 'name' },
      listQueryCategoryId: '',
      statusJson: [
        { value: 0, label: '已下架' },
        { value: 1, label: '已上架' },
        { value: 2, label: '审核中' },
        { value: 3, label: '已拒绝' },
      ],
      sampleJson: [
        { value: 0, label: '否' },
        { value: 1, label: '是' },
      ],
      typeJson: [
        { value: 1, label: '众茶通App商品' },
        { value: 2, label: '众茶通小程序商品' },
      ],
      isFinanceProductStatusJson: [
        { value: 1, label: '是' },
        { value: 0, label: '否' },
      ],
      storeList: [],
      storeId: '',
      dialogDetailVisible: false,
      detail:{},
      QRImgUrl: '',
      qrImageVisible: false,
      editDialogFormVisible: false,
      tempProduct: {
        id: '',
        marketId: '',
        price: '',
      }
    }
  },
  watch: {
    listQueryCategoryId(val) {
      this.listQuery.categoryId = this.$refs['listQueryCategoryId'].getIds(val)
    },
    storeId(val) {
      this.listQuery.storeId = val && val.length ? val[val.length - 1] : ''
    },
    $route: {
      handler: function(route) {
        const t = route.query.t;
        if (t) {
          this.getList()
        }
      },
      immediate: true
    }
  },
  created() {
    this.getList()
    this.getCategory()
    this.getStoreList()
  },
  methods: {
    getCategory() {
      categoryPageVoByQo().then((res) => {
        this.$set(this, 'categoryData', res || [])
      })
    },
    getStoreList() {
      storePageByQo().then((res) => {
        this.$set(this, 'storeList', res || [])
      })
    },
    getList() {
      this.listLoading = true

      this.productType = Number(this.paramProductType)
      
      if (this.productType == 0) {// 0:普通商品，
        this.listQuery.isSeckill = 0
        this.listQuery.type$in = '1,2'

        productPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 1) {// 1:秒杀商品，
        this.listQuery.type = '2'
        secKillProductPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 2) {// 2:经销商品 
        this.listQuery.type = '2'
        agentProductPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 3) {// 3:活动专区商品 
        this.listQuery.type = '2'
        activityProductPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 4) {// 4:微商城商品 
        this.listQuery.type = '3'
        this.listQuery.isSeckill = 0

        productPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 5) {// 5:众茶优选普通商品 
        this.listQuery.type = '4'
        this.listQuery.isSeckill = 0

        productPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 6) {// 6：众茶优选秒杀商品 
        this.listQuery.type = '4'

        secKillProductPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 7) {// 7:众茶优选推广秒杀商品 
        this.listQuery.type = '4'
        this.listQuery.isExtension= '1'

        secKillProductPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 8) {// 8:众茶优选积分商品 
        this.listQuery.type = 14

        productPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 9) {// 9:众茶优选经销商品
        this.listQuery.type = 4
        agentProductPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 10) {// 10:众茶优选专柜商品
        this.listQuery.type = '4'
        this.listQuery.isSeckill = 4

        productPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 11) {// 11:众茶优品商品
        this.listQuery.type = '5'
        this.listQuery.isSeckill = 0

        productPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      } else if (this.productType == 12) {// 12:服务商专区商品
        this.listQuery.isSeckill = 0
        this.listQuery.type$in = '1,2'
        this.listQuery.isServeProduct = 1

        productPageByQo(this.listQuery).then(response => {
          this.list = response.list || []
          this.total = response.totalCount
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
      }
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    toSave(id) {
      if (this.productType == 0) {// 0:普通商品
        this.$router.push({
          path: "/shop/normalProductSave",
          query: {
            id: id,
            productType: 0,
            isCopyZCTGood: 0
          }
        });
      } else if (this.productType == 1) {// 1:秒杀商品
        this.$router.push({
          path: "/shop/killProductSave",
          query: {
            id: id,
            productType: 1,
            isCopySecKillGood: 0
          }
        });
      } else if (this.productType == 2) {// 2:经销商品
        this.$router.push({
          path: "/customer/agentProductSave",
          query: {
            id: id,
            productType: 2
          }
        });
      } else if (this.productType == 3) {// 3:活动专区商品
        this.$router.push({
          path: "/shop/activityProductSave",
          query: {
            id: id,
            productType: 3,
            isCopyActivityGood: 0
          }
        });
      } else if (this.productType == 4) {// 4:微商城商品
        this.$router.push({
          path: "/microShop/microShopProductSave",
          query: {
            id: id,
            productType: 4
          }
        });
      } else if (this.productType == 5) {// 5:众茶优选普通商品
        this.$router.push({
          path: "/zcyx/zcyxProductSave",
          query: {
            id: id,
            productType: 5,
            isCopyActivityGood: 0
          }
        });
      } else if (this.productType == 6) {// 6：众茶优选秒杀商品
        this.$router.push({
          path: "/zcyx/zcyxProductSeckillSave",
          query: {
            id: id,
            productType: 6,
            isCopyZcyxSecKillGood: 0
          }
        });
      } else if (this.productType == 7) {// 7:众茶优选推广秒杀商品
        this.$router.push({
          path: "/zcyx/zcyxProductSeckillPopularizeSave",
          query: {
            id: id,
            productType: 7
          }
        });
      } else if (this.productType == 8) {// 8:众茶优选积分商品
        this.$router.push({
          path: "/zcyx/zcyxProductScoreSave",
          query: {
            id: id,
            productType: 8
          }
        });
      } else if (this.productType == 9) {// 9:众茶优选经销商品
        this.$router.push({
          path: "/zcyx/zcyxAgentProductSave",
          query: {
            id: id,
            productType: 9
          }
        });
      } else if (this.productType == 10) {// 10:众茶优选专柜商品
        this.$router.push({
          path: "/zcyx/zcyxBarProductSave",
          query: {
            id: id,
            productType: 10,
            isCopyZcyxBarGood: 0
          }
        });
      } else if (this.productType == 11) {//11:众茶优品商品
        this.$router.push({
          path: "/shop/bestProductSave",
          query: {
            id: id,
            productType: 11,
          }
        });
      } else if (this.productType == 12) {//12:服务商专区商品
        this.$router.push({
          path: "/shop/serviceProductSave",
          query: {
            id: id,
            productType: 12,
          }
        });
      } else {
        
      }
    },
    handleFrozen() {
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据')
        return
      }
      const params = {
        ids: this.multipleSelection.join(',')
      }
      this.$confirm('是否继续操作？').then(() => {
        productFrozen(params).then(() => {
          this.$message({
            message: '设置成功！',
            type: 'success'
          });
          this.getList()
        })
      })
    },
    // 批量操作
    handleSelectionChange(val) {
      this.multipleSelection = val.map((ele) => {
        return ele.id
      })
    },
    handlePlDelete() {
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据')
        return
      }
      const params = {
        ids: this.multipleSelection.join(',')
      }
      this.$confirm('是否继续删除？').then(() => {
        productRemoveByIds(params).then(() => {
          this.$message({
            message: '批量删除成功！',
            type: 'success'
          });
          this.getList()
        })
      })
    },
    checkStore() {
      this.$router.push('/store')
    },
    handleDetail(row) {
      this.getDetail(row).then(res => {
        this.detail = Object.assign({}, res)
        this.dialogDetailVisible = true;
      })
    },
    getDetail(row) {
      return new Promise((resolve, reject) => {
        let param = {id: row.id}
        if (row.marketId) {
          param.marketId = row.marketId
        } else {
          param.marketId = ''
        }

        productGetById(param).then(res => {
          resolve(res);
        })
        .catch(err => {
          reject(err);
        });
      });
    },
    uploadZCTProduct(id) {
      this.$router.push({
    		path: "/shop/normalProductSave",
    		query: {
    			id: id,
          productType: 0,
          isCopyZCTGood: 1
    		}
    	});
    },
    uploadSecKillProduct(id) {
      this.$router.push({
    		path: "/shop/killProductSave",
    		query: {
    			id: id,
          productType: 1,
          isCopySecKillGood: 1
    		}
    	});
    },
    uploadZcyxSecKillProduct(id) {
      this.$router.push({
        path: "/zcyx/zcyxProductSeckillSave",
        query: {
          id: id,
          productType: 6,
          isCopyZcyxSecKillGood: 1
        }
      });
    },
    uploadActivityProduct(id) {
      this.$router.push({
    		path: "/shop/activityProductSave",
    		query: {
    			id: id,
          productType: 3,
          isCopyActivityGood: 1
    		}
    	});
    },
    uploadZcyxBarProduct(id) {
      copyProductToCounter({ id: id}).then(res => {
        this.$router.push({
          path: "/zcyx/zcyxBarProductSave",
          query: {
            id: res,
            productType: 10,
            isCopyZcyxBarGood: 1
          }
        });
      })
      .catch((err) => {
        console.log(err)
      })
    },
    uploadZcyxAgentProduct(id) {
      this.$router.push({
        path: "/zcyx/zcyxAgentProductSave",
        query: {
          id: id,
          productType: 9,
          isCopyZcyxAgentGood: 1
        }
      });
    },
    getQRcode(row) {
      if (row.qrcode) {
        this.QRImgUrl= row.qrcode
        this.qrImageVisible = true
      } else {
        getBarProductQrcode({ productId: row.id}).then(res => {
          this.QRImgUrl= res
          this.qrImageVisible = true
        })
        .catch((err) => {
          console.log(err)
        })
      }
    },
    closeViewer() {
      this.qrImageVisible = false
    },
    // 众茶优品修改价格
    handleEditPrice(row) {
      this.tempProduct.id = row.id
      this.tempProduct.marketId = row.marketId
      this.editDialogFormVisible = true
    },
    finishEditPrice() {
      productSave(this.tempProduct, true).then(() => {
        this.editDialogFormVisible = false
        this.handleFilter()
      }).catch((err) => {
        console.log(err)
      })
    },
    handlePriceInput(v, row, param) {
      let newValue = v.toString()
      newValue = v
        .replace(/[^\d.]/g, '')
        .replace(/\.{2,}/g, '.')
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      if (
        newValue.length > 1 &&
        newValue.indexOf('.') !== 1 &&
        newValue.indexOf('0') === 0
      ) {
        newValue = newValue.toString().substring(1)
      }
      row[param] = newValue
      this.$nextTick(() => {
        this.$forceUpdate()
      })
      return newValue
    },
  }
}
</script>
